<template>
  <div>
    <component
      :is="page"
      v-for="page in pageSetting.page"
      :key="page"
      :ref="page"
      :prj-stage="workDetail.bizObject.wfStage || 'F'"
      :prj-type="prjDetail.prjType"
      :process-inst-id="processInstId"
      :prj-id="prjDetail.prjId"
      :hq-type="hqType"
      :activityDefID="workDetail.activityDefID"
    />
    <t-page-btn v-if="type === 'todo' && btnList.length > 0" :btn-list="btnList" @handleBtn="handleBtn" />
    <!-- 下一步 -->
    <next-page
      v-if="nextVisible"
      ref="nextPage"
      :visible.sync="nextVisible"
      :activity-inst-id="workDetail.activityInstID"
      :process-inst-id="workDetail.processInstID"
      :activity-def-id="workDetail.activityDefID"
      :process-def-name="workDetail.processDefName"
      :route="this.routeType"
      :loginName="loginName"
      :prj-id="prjDetail.prjId"
      @doNextEntity="nextPageRes"
    />
    <!-- 回退 -->
    <Back-page
      v-if="backVisible"
      ref="backPage"
      :visible.sync="backVisible"
      :process-inst-id="workDetail.processInstID"
      :act-inset-id="workDetail.activityInstID"
      :exclude-act-def-ids="excludeActDefIds"
      :route="backRoute"
      @doReturn="backPageRes"
    />
    <!-- 转派 -->
    <TransferPage
      v-if="transferPageVisible"
      :visible.sync="transferPageVisible"
      :process-inst-id="workDetail.processInstID"
      :org-id="workDetail.orgId"
      :org-code="workDetail.orgCode"
      @redeployEntity="redeployEntity"
    />
    <!-- 弹窗 -->
    <DialogConfirm v-if="dialogVisible" :message="[dialogMessage]" @changeStatus="changeMsg" />
    <!-- 校验清单 -->
    <el-dialog
      v-if="checkDialog"
      title="校验清单"
      :visible.sync="checkDialog"
      class="pms-zr-dialog"
      width="50%"
      :before-close="closeDialog"
    >
      <interior-verify :select-list="interiorData" single="1" :check-materials="false" />
    </el-dialog>
    <!-- 物资总览查看新页面 -->
    <el-dialog
      v-if="checkMaterials"
      title="物资服务总览"
      :visible.sync="checkMaterials"
      class="pms-zr-dialog"
      width="90%"
      :before-close="closeMaterialsDialog"
      height="60%"
    >
      <interior-verify :select-list="interiorData" single="1" :check-materials="true" />
    </el-dialog>
    <!-- 设备变动信息 -->
    <el-dialog
      v-if="showEquipmentChange"
      title="设备变动信息"
      :visible.sync="showEquipmentChange"
      class="pms-zr-dialog"
      width="90%"
      :before-close="closeDialog"
    >
        <div style="max-height: 600px;overflow-y: auto">
            <equipmentChange @deviceDoNext="closeEquipmentChange"/>
        </div>
    </el-dialog>
  </div>
</template>
<script>
import { Loading } from 'element-ui'
import DialogConfirm from '@/views/acceptanceManagement/materialServiceBind/components/dialogConfirm.vue'
import { pageSettings,newpageSettings} from './setting'
import { clonePage, enableScroll, getQueryObject, msgInfoEl, setDocTitle } from '@/utils'
import JnPrjDetail from '@/components/jn/JnPrjDetail.vue'
import JnSiteDetail from '@/components/jn/JnSiteDetail.vue'
import JnTaskDetail from '@/components/jn/JnTaskDetail.vue'
import JnCountersign from '@/components/jn/JnCountersign.vue'
import JnSingleList from '@/components/jn/JnSingleList.vue'
import ZrAttachmetl from '@/components/zr/ZrAttachmetl.vue'
import ProjectExclusiveinfo from '@/components/jn/JnProprietaryDetail'
import singleStationEntering from './components/singleStation/entering.vue'
import singleStationCheck from './components/singleStation/check.vue'
import singleStationAffirm from './components/singleStation/affirm.vue'
import singleStationReplace from './components/singleStation/replace.vue'
import entiretyMain from './components/entirety/main.vue'
import entiretyEntering from './components/entirety/entering.vue'
import entiretyCheck from './components/entirety/check.vue'
import schedule from './schedule.vue'
import mainSingle from './components/entirety/mainSingle.vue'
import enteringSingle from './components/entirety/enteringSingle.vue'
import affirmSingle from './components/entirety/affirmSingle.vue'
import checkSingle from './components/entirety/checkSingle.vue'
import goods from './goods.vue'
import microstation from './microstation.vue'
import plan from './plan.vue'
import interiorVerify from './interior.vue'
import materialService from './materialService/index.vue'
import showSingle from './components/show/single.vue'
import showEntiretyItem from './components/show/entiretyItem.vue'
import showEntirety from './components/show/entirety.vue'
import ZrMaterialService from '@/components/zr/ZrMaterialService.vue'
import materialServiceDetail from './materialService/page.vue'
import ReceiptInfo from './receipt/receiptInfo.vue'
import {
  backActivityApi,
  doNextFLowApi,
  getWFWorkItemApi,
  hqBtnNext,
  updateItAcceptTime
} from '@/api/acceptanceManagement/acceptanceMange'
import {
    executeFailureToUpdateApi,
    executeVerificationApi,
    getPrjDetailApi,
    getVerificationListApi, updateAcceptTimeApi, getIsDeployCountersignature, getShowEquipmentChangeApi,getSelectUser,getSelectUserNextRT
} from '@/api/acceptance/index'
import BackPage from '@/components/nextPerson/BackPage.vue'
import TPageBtn from '@/components/basic/TPageBtn.vue'
import NextPage from '@/components/nextPerson/NextPage.vue'
import TransferPage from '@/components/nextPerson/ReassignPageNew.vue'
import store from '@/store'
import equipmentChange from "@/views/acceptance/components/equipmentChange.vue";
import ZrPmsCheckInspection from "./otherPage/ZrPmsCheckInspection.vue"
import ZrPmsCheckWorkload from './otherPage/ZrPmsCheckWorkload.vue'
const pageTitle = {
  'F4': '资源录入',
  'F5': '资源确认',
  'F1': '内部验收',
  'F7': '关闭审核',
  'I2': '会签'
}
const pageTitleSecond = {
  'F4': '资源录入',
  'F1': '部门审核'
}
const pageTitleThird = {
  'F1': '内部验收',
  'F12': '项目接维',
  'RT1':'项目整改'
}
export default {
  components: {
    showSingle,
    showEntirety,
    showEntiretyItem,
    materialServiceDetail,
    NextPage, TPageBtn, BackPage,
    JnPrjDetail,
    JnSiteDetail,
    JnTaskDetail,
    JnCountersign,
    ZrAttachmetl,
    schedule,
    JnSingleList,
    mainSingle,
    goods,
    microstation,
    singleStationEntering,
    singleStationReplace,
    singleStationCheck,
    singleStationAffirm,
    entiretyMain,
    enteringSingle,
    entiretyEntering,
    affirmSingle,
    checkSingle,
    entiretyCheck,
    plan,
    interiorVerify,
    materialService,
    ZrMaterialService,
    DialogConfirm,
    TransferPage,
    ProjectExclusiveinfo,
    equipmentChange,
    ReceiptInfo,
    ZrPmsCheckInspection,
    ZrPmsCheckWorkload
  },
  data() {
    return {
      pageSettings,
      newpageSettings,
      dialogVisible: false,
      dialogMessage: '',
      currentParams: '',
      nextVisible: false,
      backVisible: false,
      transferPageVisible: false,
      excludeActDefIds: '',
      backRoute: '1',
      prjDetail: {},
      workDetail: {
        bizObject: {}
      },
      type: '',
      processInstId: '',
      checkList: {},
      currentCheck: {},
      btnList: [],
      pageSetting: [],
      interiorData: [],
      checkDialog: false,
      showEquipmentChange: false,
      hqType: false,
      routeType: '1', // 下一步route参数
      materialsCode: '', // 新页面物资总览code
      checkMaterials: false, // 物资总览弹框是否打开
      countersignDetail:{},
      loading:'',
      zgPrjList:[]
    }
  },
  computed:{
    getxianchaiShow(){
      return this.prjDetail.isNewBusiness === '0'&&this.prjDetail.businessMajor==='04'&&this.prjDetail.buildModes==='27'
    },
    loginName(){
      return +this.prjDetail.isNewAcceptance === 1&&this.workDetail.bizObject.bizState==='F12'&&this.zgPrjList?.confirm === 'Z' ? this.prjDetail.projectManagerName + `(${this.prjDetail.projectManagerLoginName})` : ''
    }
  },
  provide() {
    return {
      prjDetail: () => this.prjDetail,
      workDetail: () => this.workDetail,
      countersignDetail: () => this.countersignDetail
    }
  },
  created() {
    const { workItemId, prjId, type, processInstId } = getQueryObject()
    this.type = type
    this.processInstId = processInstId
    if (workItemId) {
      this.getWorkItem(workItemId)
    }
    if (prjId) {
      this.getPrjDetail(prjId)
    }

    window.addEventListener('message', (event) => {
      const base_url = ''
      if (event.origin === base_url) {
        return
      }
      // console.log('接受的信息', event.data)
      if (event.data.type === 'initNextInfo') {
        if (event.data.single) {
          this.materialsCode = event.data.doNext
          this.queryParams()
        }
      }
      if (event.data.type === 'interiorVerify') {
        this.close()
      }
      if (event.data.type === 'closeCheckDialog') {
        this.checkDialog = false
      }
    })
  },
  methods: {
    closeEquipmentChange(){
      this.showEquipmentChange = false
      this.nextVisible = true
    },
    dialogClosed() {
      const contentBody = window.top.document.body
      enableScroll(contentBody)
    },
    async getWorkItem(workItemId) {
      const result = await getWFWorkItemApi(workItemId)
      this.workDetail = result.data
      const { bizObject, processInstID } = result.data
      const { prjId, buttonConfig, bizState } = bizObject
      console.log(bizState, 'bizState')
      // 如果是会签让项目验收信息按钮不显示
      this.hqType = bizState !== 'I2'
      this.processInstId = processInstID
      // 如果是会签则只显示下一步 否则用原来的逻辑  后期需要回退和转派 直接使用原有的逻辑 增加三个 新方法就可以
      this.btnList = JSON.parse(buttonConfig) || []
      this.getPrjDetail(prjId)
    },
    optimizeNewgetPrjDetailOne(){
      return this.optimizeNewOne() && this.optimizeNewTwo()
    },
    optimizeNewgetPrjDetailTwo(flags){
        const manageMode = this.getManageMode();
        if (+this.prjDetail.isNewAcceptance === 1) {
            const result = this.newpageSettings['show'][manageMode]
            // 综合查询过交维才可以看
            const res = result.page.filter(item => item !== 'ReceiptInfo')
            return +this.prjDetail.isReceiveMaintain===1 ? result : {page: res}
        } else {
            return this.pageSettings[flags ? 'newshow' : 'show'][manageMode]
        }
    },
    optimizeNewgetPrjDetailThree(pageSetting){
      return pageSetting.page.filter(item => !(this.type === 'done' && item === 'JnCountersign'))
    },
    optimizeNewgetPrjDetailFour(){
      return this.prjDetail.isNewBusiness === '1' && this.prjDetail.manageMode === '03'
    },
    optimizeNewgetPrjDetailFive(){
      return this.prjDetail.isNewBusiness === '1' && this.workDetail?.bizObject?.bizState === 'F1'
    },
    optimizeNewgetPrjDetailSix(flags,pageTitleSecond_,pageTitle_){
      if(+this.prjDetail.isNewAcceptance === 1){
        return  pageTitleThird[this.workDetail?.bizObject?.bizState]
      }else{
        return flags ? pageTitleSecond_[this.workDetail?.bizObject?.bizState] : pageTitle_[this.workDetail?.bizObject?.bizState]
      }
    },
    optimizeNewgetPrjDetailCancelBack(){
     if (this.optimizeNewgetPrjDetailOne() || ['51', '05'].includes(this.prjDetail.manageMode) || this.getServeCost()) {
       this.btnList = this.btnList.filter(item => item.method !== 'doBack')
     }
      if(+this.prjDetail.isSimpleAcceptance===1){
      this.btnList = this.btnList?.filter(item => item?.method !== 'doBack')
     }
   },
    //  能源重构
    async getPrjDetailNengYuan(flags,pageSetting) {
      let _newpageSetting = pageSetting.page
      if (this.optimizeNewgetPrjDetailFour()) {
        _newpageSetting = pageSetting.page.filter(item => !(['JnSiteDetail'].includes(item)))
      }
      // 研发项目
      if (flags) {
        _newpageSetting = pageSetting.page.filter(item => !(['JnSiteDetail', 'schedule'].includes(item)))
      }
      return _newpageSetting
     },
     //  是否会签配置
     async getIsCountersignature() {
      const params = {
        prjId: this.prjDetail.prjId,
        nodeState: this.workDetail?.bizObject?.bizState,
        manageMode: this.prjDetail.manageMode
      }
      const { code, data } = await getIsDeployCountersignature(params)
      if (+code !== 200) {
        return
      }
      this.countersignDetail = data
      console.log(this.countersignDetail, '是否会签');
      return data.showCounterSign
    },
    //判断是否新流程
     isNewProcess(){
         const manageMode = this.getManageMode();
         if (+this.prjDetail.isNewAcceptance === 1) {
             return this.newpageSettings[manageMode][this.workDetail?.bizObject?.bizState]
         } else {
             return this.pageSettings[manageMode][this.workDetail?.bizObject?.bizState]
         }
    },
    // 查看页面是否是服务成本
    getServeCost(){
        return this.prjDetail.manageMode === '01' && this.prjDetail.prjType === 'W' && this.prjDetail.buildModes === '25' && this.prjDetail.isSingleAccounting === '1'
    },
    //软件开发和服务成本页面配置待办
     getSoftDevelop(pageSetting) {
        if(['51', '05'].includes(this.prjDetail.manageMode)){
            if(this.prjDetail.manageMode === '05'){
              //添加站址信息。
              pageSetting.page.splice(2, 0, 'JnSiteDetail')
            }
            if(this.prjDetail.manageMode === '51'){
              //子项目删掉物资，
              pageSetting.page = pageSetting.page.filter(children => children !== 'goods')
            }
            //满足软件开发类，购买服务  需要删除进度计划信息
            pageSetting.page = pageSetting.page.filter(children => children !== 'schedule')
        }else if(this.getServeCost()){
            pageSetting.page = pageSetting.page.filter(children => children !== 'schedule')
        }else{
            console.log('啥也不干')
        }
        return pageSetting
    },
    //软件开发和服务成本页面配置综合查询
    getSoftDevelopDone(pageSetting){
        if(['51', '05'].includes(this.prjDetail.manageMode)){
            //满足软件开发类  主项目需要添加子项目列表  走03配置时候，需要删除多余配置
            if(this.prjDetail.manageMode === '03'){
                pageSetting.page.splice(2, 0, 'JnSiteDetail')
            }
            //子项目  走31配置，无子项目列表
            if(this.prjDetail.manageMode === '51'){
                pageSetting.page = pageSetting.page.filter(children => children !== 'materialServiceDetail')
            }
            //满足软件开发类，购买服务  需要删除进度计划信息
            pageSetting.page = pageSetting.page.filter(children => children !== 'schedule')
        }else if(this.getServeCost()){
            pageSetting.page = pageSetting.page.filter(children => children !== 'schedule')
        }else{
            console.log('啥也不干')
        }
        return pageSetting
    },
    getManageMode(){
        if(this.prjDetail.manageMode === '51'){
            return '31'
        }else if(this.prjDetail.manageMode === '05'){
            return '03'
        }else{
            return this.prjDetail.manageMode
        }
    },
    async getPrjDetail(id) {
      const res = await getPrjDetailApi(id)
      this.prjDetail = res.data
      const deployCountersignature = await this.getIsCountersignature()
      // 判断 是否是研发类项目
      const flags = this.prjDetail.prjType === 'Y'
      await this.optimizeNewgetPrjDetailCancelBack()
      if (this.workDetail?.bizObject?.bizState) {
        //通信维护新流程
        const pageSetting =  this.isNewProcess()
        console.log(this.prjDetail.manageMode, this.workDetail?.bizObject?.bizState, '页面',pageSetting)
        pageSetting.page = this.optimizeNewgetPrjDetailThree(pageSetting)
        pageSetting.page = await this.getPrjDetailNengYuan(flags, pageSetting)
        pageSetting.page = pageSetting.page.filter(children => children !== 'JnCountersign')
        if (deployCountersignature) {
          pageSetting.page.splice(pageSetting.page.length - 2, 0, 'JnCountersign')
          console.log(pageSetting,'会签流程配置');
        }
        this.pageSetting = this.getSoftDevelop(pageSetting)
        console.log(1234,this.pageSetting)
        this.getNewPageSeetingOnly() 
        const PageTitles = this.optimizeNewgetPrjDetailSix(flags, pageTitleSecond, pageTitle)
        store.commit('settings/setPageTitle', `${this.workDetail?.processInstName}-验收-${PageTitles}`)
      } else {
        // 综合查询
        // this.pageSetting = this.optimizeNewgetPrjDetailTwo(flags)
        const pageSetting = this.optimizeNewgetPrjDetailTwo(flags)
        this.pageSetting = this.getSoftDevelopDone(pageSetting)
        this.getNewPageSeetingOnlyQuery()
      }
    },
    getNewPageSeetingOnlyQuery() {
      const _index =  this.pageSetting.page.indexOf('ZrAttachmetl')
      if (['05','51'].includes(this.prjDetail.manageMode)) {
        this.pageSetting.page.splice(_index, 0, 'ZrPmsCheckWorkload')
      }
      if (this.getServeCost()) {
        this.pageSetting.page.splice(_index, 0, 'ZrPmsCheckInspection')
      }
    },
    getNewPageSeetingOnly() {
      const _index =  this.pageSetting.page.indexOf('ZrAttachmetl')
      if (['05','51'].includes(this.prjDetail.manageMode)) {
        this.pageSetting.page.splice(_index, 0, 'ZrPmsCheckWorkload')
      }
      if (this.getServeCost()) {
        this.pageSetting.page.splice(_index, 0, 'ZrPmsCheckInspection')
      }
    },
    // 2024-9-26 阻断问题if过多解决方案
    optimizeNewOne() {
      return ['1','2'].includes(this.prjDetail.isNewBusiness) && this.prjDetail.ifNewStartupProcess === '1' && this.prjDetail.isMaintain === '0'
    },
    optimizeNewTwo() {
      return this.prjDetail.manageMode === '03' && this.workDetail?.bizObject?.bizState === 'F1'
    },
    async doNext() {
      //  会签确认回调函数
      if (!this.hqType) {
        this.doNextHq()
        return
      }
      await this.save(true)
      const params = {
        'prjId': this.prjDetail.prjId,
        'nodeState': this.workDetail.bizObject.bizState
      }
      const result = await getVerificationListApi(params)
      this.checkList = result.data
      this.loading = Loading.service({
        lock: true,
        text: '正在处理,请稍后',
        spinner: 'el-icon-loading'
      })
      this.queryParams()
    },
    doBack() {
      //  会签确认回调函数
      if (!this.hqType) {
        this.doBacktHq()
        return
      }
      this.excludeActDefIds = ''
      this.backRoute = '1'
      this.backVisible = true
    },
    // 前置校验
    async queryParams() {
      this.zgPrjList = []
      this.checkMaterials = false
      const { data, ysCode } = this.checkList
      // 内部校验弹出校验列表,其他的进行选择节点
      if (!data?.length) {
        this.loading.close()
        this.optimizeNewthree()
        return
      }

      this.currentCheck = data.shift()
      const params = {
        'prjInfos': [{
          siteId: this.prjDetail.siteId,
          prjCode: this.prjDetail.prjCode,
          prjId: this.prjDetail.prjId,
          workItemId: this.workDetail.workItemID,
          manageMode: this.prjDetail.manageMode,
          prjType: this.prjDetail.prjType,
          isNewBusiness: this.prjDetail.isNewBusiness,
          buildModes: this.prjDetail.buildModes,
          parentPrjId: this.prjDetail.parentPrjId,
          bizState: this.workDetail.bizObject.bizState,
          bizSeq: this.workDetail.bizObject.bizState === 'RT1' ? this.workDetail.bizObject.bizSeq : ''
        }],
        'code': this.currentCheck.code,
        'operateFlag': this.prjDetail.manageMode === '31' || this.prjDetail.manageMode === '51' ? 1 : 2, // 单项工程1,其他2
        'ysCode': ysCode
      }
      const result = await executeVerificationApi(params)
      if (+result.code === 200) {
        this.queryParams()
        return
      }
      if (result.data.confirm === 'P') {
        this.loading.close()
        this.currentParams = result.data.data
        this.dialogMessage = result.message
        this.dialogVisible = true
        return
      }
       if (result.data.confirm === 'B') { // 回退
        this.loading.close()
        msgInfoEl({
          type: 'error',
          message: result.message
        }, 3000)
        this.excludeActDefIds = result.data.excludeActDefIds
        this.backRoute = 'more'
        this.backVisible = true
        return
      }
      // 项目接维 打开下一步
      if (this.workDetail.bizObject.bizState === 'F12'&&result.data.confirm === 'Z') {
        this.zgPrjList = result.data
        this.loading.close()
        this.nextVisible = true
        return
      }
      this.loading.close()
      msgInfoEl({
        type: 'error',
        message: result.message
      }, 3000)
      // this.$message.error(result.message)
    },
    getCheckOpenEquipmentParams(){
        let params
        if(this.prjDetail.manageMode === '01'){
            //单站项目下一步  getAcceptPrjInfo接口返回的prjId为prjId、子项目集合为空
            params={
                prjId:this.prjDetail.prjId,
                ifSingleProject: '0',
                subPrjIds:[],
            }
        }else if(this.prjDetail.manageMode === '31'){
            //单项工程下一步 getAcceptPrjInfo接口返回的prjId为子项目集合，parentPrjId为prjId，
            const list=[];
            list.push(this.prjDetail.prjId)
            params={
                prjId:this.prjDetail.parentPrjId,
                ifSingleProject: '1',
                subPrjIds:list,
            }
        }else{
            //无实施整体项目下一步 单项工程列表所有数据为子项目集合，parentPrjId取其中一个
            const list=[]
            const _tableData = JSON.parse(window.sessionStorage.getItem('TableprjInfos')) || []
            for (let i = 0; i < _tableData?.length; i++) {
                list.push(_tableData[i]?.prjId)
            }
            params={
                prjId:_tableData[0]?.parentPrjId,
                ifSingleProject: '1',
                subPrjIds:list,
            }
        }
        return params;
    },
    checkShowEquipmentChange(){
        let params=this.getCheckOpenEquipmentParams();
        //调接口,返回true则展示弹窗，否则展示下一步的选人弹窗
        console.log('params',params)
        getShowEquipmentChangeApi(params).then((res)=>{
            if(+res.code === 200){
                if(res.data?.length > 0){
                    // this.equipmentPrjIds = res.data;
                    window.sessionStorage.setItem('equipmentPrjIds', JSON.stringify(res.data))
                    this.showEquipmentChange=true
                }else{
                    this.nextVisible = true
                }
            }
        })
    },
    checkOpenEquipmentDialog(){
      //维护专业，资源确认
        console.log(1111,this.prjDetail.prjId,this.prjDetail.parentPrjId)
      if(['F5','F12'].includes(this.workDetail.bizObject.bizState) && this.prjDetail.isNewBusiness === '0' && this.prjDetail.businessMajor === '04'){
          //单站项目、单项工程、无实施整体项目
          if(this.prjDetail.manageMode === '01'||this.prjDetail.manageMode === '31'||(this.prjDetail.manageMode === '03' && this.prjDetail.ifNewStartupProcess === '1')){
              this.checkShowEquipmentChange();
          }else{
              this.nextVisible = true
          }
      }else{
          this.nextVisible = true
      }
    },
    // 2024-9-26 阻断问题if过多解决方案
    optimizeNewthree() {
      if (this.workDetail.bizObject.bizState === 'F1') {
          this.interiorData = [
            {
              prjId: this.prjDetail.prjId,
              prjCode: this.prjDetail.prjCode,
              siteId: this.prjDetail.siteId,
              workItemId: this.workDetail.workItemID,
              manageMode: this.prjDetail.manageMode,
              prjType: this.prjDetail.prjType,
              isNewBusiness: this.prjDetail.isNewBusiness,
              buildModes: this.prjDetail.buildModes,
              parentPrjId: this.prjDetail.parentPrjId,
              bizState: this.workDetail.bizObject.bizState // 根据点击的按钮来决定
            }
          ]
          const _tablesinfo = JSON.parse(window.sessionStorage.getItem('TableprjInfos')) || []
          const SingeZhengti = this.optimizeIfSolveOne(_tablesinfo)
          // 单站的内部验收和整体内部验收不一样
         const isHiddenMatria = this.optimizeIfSolveTwo(SingeZhengti,_tablesinfo)
          // 下一步首先弹出物资总览查看新页面=>在下一步以后才可以打开校验清单页面
          if (+this.materialsCode !== 200 && isHiddenMatria) {
            // 服务成本-设备录入不涉及物资
            this.checkMaterials = true
            return
          }
          this.checkDialog = true
        } else {
          this.checkOpenEquipmentDialog();
          // this.nextVisible = true
        }
    },
     // 2024-9-26 阻断问题if过多解决方案
     optimizeIfSolveOne(_tablesinfo) {
      return !(_tablesinfo[0]?.prjType === 'W' && this.prjDetail.buildModes === '26')
     },
     optimizeIfSolveTwo(SingeZhengti,_tablesinfo) {
      if(this.getxianchaiShow){
        return false
      }
       if(['51', '05'].includes(this.prjDetail.manageMode) || this.getServeCost()){
         return false
       }
      if (this.prjDetail.ifOnlineServ === '0') {
        return this.optimizeIfSolveThree(_tablesinfo)
      } else {
        return this.prjDetail.manageMode === '01' ? this.optimizeIfSolveTwoNengYuan() : SingeZhengti
      }
     },
    //  单站-能源
    optimizeIfSolveTwoNengYuan(){
      return !(this.prjDetail.prjType === 'W' && this.prjDetail.buildModes === '26')
    },
    // 清单设计不涉及物资总览
    optimizeIfSolveThree(_tablesinfo) {
      if (this.prjDetail.manageMode === '01' && this.prjDetail.prjType === 'W' && this.prjDetail.buildModes === '25') {
        return false
      }
      if (_tablesinfo[0]?.prjType === 'W' && _tablesinfo[0]?.buildModes === '25') {
        return false
      }
    },
    async dialogSubmit() {
      this.dialogVisible = false
      const params = {
        prjInfos: this.currentParams,
        code: this.currentCheck.code,
        operateFlag: this.prjDetail.manageMode === '31' || this.prjDetail.manageMode === '51' ? 1 : 2,
        ysCode: this.checkList.ysCode
      }
      const result = await executeFailureToUpdateApi(params)
      if (+result.code === 200) {
        this.queryParams()
      }
    },
    handleBtn(methodName) {
      console.log(methodName)
      this[methodName]()
    },
    // 确认下一步 getSelectUser
    zgBtnNextPageRes(data){
      const params = {
        prjId: this.zgPrjList.failPrjList?.map(item => item.prjId).join(','),
        sceneCode:'SC_ACC_ZG_001',
        currentUserId:data.empId||this.prjDetail?.projectManagerLoginName,
        staffId:data.code ||this.prjDetail?.projectManager
      }
      getSelectUser(params).then(res => {
        if (+res.code === 200) {
          this.close()
        }
      })
    },
    async nextPageRes(data) {
      //  会签确认回调函数
      if (!this.hqType) {
        this.hqBtnNextPageRes(data)
        return
      }
      if(this.zgPrjList.confirm === 'Z'){
        this.zgBtnNextPageRes(data)
        return
      }
      const params = {
        'prjId': this.prjDetail.prjId,
        'workItemId': this.workDetail.workItemID,
        'userIds': data.empId,
        'route': '1', // 下一步页面
        'wfXpath': [], // 暂时不传
        'opinion': data.opinion,
        'nextSceneId': data.nextSceneId, // 先不传
        'nodeId': data.nodeId,
        'detailId': data.detailId, // 先不传
        'route1': '1', // 决算页面
        'activityDefId': data.actDefId, // 当前节点
        'finish': data.finish, // 当前节点
        'templateId': data.nTemplateId
      }
      if (this.workDetail?.bizObject?.bizState === 'RT1') {
        const _newParams = {
          ...params,
          bizSeq: this.workDetail.bizObject.bizSeq
        }
        getSelectUserNextRT(_newParams).then(_res => {
          if (+_res.code === 200) {
            this.close()
          }
        })
        return
      }
      console.log(params)
      doNextFLowApi(params).then(res => {
        if (+res.code === 200) {
          this.close()
        }
      })
    },
    backPageRes(data) {
      if (!this.hqType) {
        this.hqBtnBackPageRes(data)
        return
      }
      const params = {
        'workItemId': this.workDetail.workItemID,
        'opinion': data.opinion,
        'nextActDefId': data.nodeId, // 暂定
        'detailId': data.empId,
        'prjId': this.prjDetail.prjId,
        'activityDefId': this.workDetail.activityDefID
      }
      backActivityApi(params).then(res => {
        if (+res.code === 200) {
          this.close()
        }
      })
    },
    getEndInternalAcceptDate(){
      if(['51', '05'].includes(this.prjDetail.manageMode)){
        return true;
      }
      if(this.getServeCost()){
        return true;
      }
      return false;
    },
    // 保存按钮
    async save(msg) {
      const qizuTime = window.sessionStorage.getItem('qizuTime') || ''
      console.log('保存')
      if (this.prjDetail.prjType === 'Y' || this.getEndInternalAcceptDate()) {
        await this.optimizeSaveYanfa(msg)
        return
      }
      let params = {}
      for (const argumentsKey of this.pageSetting.submitPage) {
        if (!this.$refs[argumentsKey]?.length) {
          continue
        }
        const result = this.$refs[argumentsKey][0].submit()
        if (result.code !== 200) {
          this.$message.error('请选择对应的时间')
          // eslint-disable-next-line no-throw-literal
          throw '校验失败'
        }
        if (JSON.stringify(result.data) !== '{}') {
          params.prjId = this.prjDetail.prjId
          params = { ...params, ...result.data,rentableOperateTime: qizuTime }
        }
      }
      if (JSON.stringify(params) === '{}') {
        return this.optimizeMessage(msg)
      }
     await this.optimizeSaveOne(params,msg)
    },
    // 2024-9-26 阻断问题if过多解决方案
   async optimizeSaveYanfa(msg) {
      let _savesData
      if(this.prjDetail.manageMode === '05'){
        _savesData = this.$refs['entiretyMain'][0].submit()
      }else{
        _savesData = this.$refs[this.pageSetting.submitPage][0].submit()
      }
        if (_savesData.data?.endInternalAcceptDate == null) {
          this.$message.error('请选择对应的时间')
          // eslint-disable-next-line no-throw-literal
          throw '校验失败'
        }
       await this.optimizeSaveTime(_savesData,msg)
    },
   async optimizeSaveTime(_savesData,msg){
      const _params = {
          prjId: this.prjDetail.prjId,
          ..._savesData.data
      }
      if(this.getEndInternalAcceptDate()){
          const qizuTime = window.sessionStorage.getItem('qizuTime') || ''
          if(this.getServeCost()){
              const params = { ..._params, rentableOperateTime: qizuTime }
             await this.optimizeSaveOne(params,msg)
              console.log('需要做异步处理')
          }else{
             await this.optimizeSaveOne(_params,msg)
              console.log('需要做异步处理')
          }
      }else{
          updateItAcceptTime(_params).then(res => {
              if (+res.code === 200) {
                  if (!msg) {
                      this.$message.success('保存成功')
                  }
              }
          })
      }
    },
    // 2024-9-26 阻断问题if过多解决方案
   async optimizeSaveOne(params,msg) {
      const result = await updateAcceptTimeApi(params)
      // eslint-disable-next-line no-throw-literal
      if (+result.code !== 200) {
        throw '校验失败'
      }
      if (!msg) {
        this.$message.success('保存成功')
      }
    },
    optimizeMessage(msg) {
      if (!msg) {
          this.$message.warning('没有要保存的内容')
        } else {
          return true
        }
    },
    // 关闭
    close() {
      clonePage()
    },
    // 关闭弹框提示消息不销毁问题
    closeDialog() {
      const body = document.body
      const _message = body.getElementsByClassName('el-message')
      if (_message && _message.length > 0) {
        for (let i = 0; i < _message.length; i++) {
          body.removeChild(_message[i])
          this.closeDialog()
        }
      } else {
        this.checkDialog = false
        this.showEquipmentChange = false
        this.materialsCode = ''
      }
    },
    // 关闭查看物资总览弹框
    closeMaterialsDialog() {
      const body = document.body
      const _message = body.getElementsByClassName('el-message')
      if (_message && _message.length > 0) {
        for (let i = 0; i < _message.length; i++) {
          body.removeChild(_message[i])
          this.closeMaterialsDialog()
        }
      } else {
        this.checkMaterials = false
      }
    },
    changeMsg(status) {
      this.dialogVisible = false
      if (status) {
        this.dialogSubmit()
      }
    },
    // 会签下一步
    doNextHq() {
        if (this.workDetail.activityDefID !== 'counter01') {
          this.nextVisible = true
          this.routeType = '0'
          return
        }
      this.$confirm(`是否结束会签流程?`, '系统提示', {
        showClose: false,
        dangerouslyUseHTMLString: true,
        confirmButtonText: '是',
        cancelButtonText: '否',
        cancelButtonClass: 'pms-zr-button',
        confirmButtonClass: 'pms-zr-button-primary',
        type: 'warning'
      }).then(() => {
        this.nextVisible = true
        this.routeType = '1'
      }).catch(() => {
        this.nextVisible = true
        this.routeType = '0'
      })
    },
    // 会签确认下一步等按钮逻辑操作
    async hqBtnNextPageRes(data) {
      // 参数
      const params = {
        'workItemId': this.workDetail.workItemID,
        'userIds': data.empId,
        'opinion': data.opinion,
        'bizSeq': this.workDetail?.bizObject?.bizSeq,
        'dealType': 'next',
        'route': this.routeType // 下一步页面
      }
      // 关闭按钮
      const { code } = await hqBtnNext(params)
      if (+code === 200) {
        this.close()
      }
    },
    doBacktHq() {
      this.backVisible = true
    },
    // 确认回退调接口
    async hqBtnBackPageRes(data) {
      // 参数
      const params = {
        'workItemId': this.workDetail.workItemID,
        'opinion': data.opinion,
        'bizSeq': this.workDetail?.bizObject?.bizSeq,
        'dealType': 'back',
        'nextActDefId': data.nodeId
      }
      // 关闭按钮
      const { code } = await hqBtnNext(params)
      if (+code === 200) {
        this.close()
      }
    },
    // 转派
    async redeployEntity(data) {
      // 参数
      const params = {
        'workItemId': this.workDetail.workItemID,
        'userIds': data.empId,
        'opinion': data.opinion,
        'bizSeq': this.workDetail?.bizObject?.bizSeq,
        'dealType': 'reassign'
      }
      // 关闭按钮
      const { code } = await hqBtnNext(params)
      if (+code === 200) {
        this.close()
      }
    },
    // 会签转派
    doReassign() {
      this.transferPageVisible = true
    }
  }
}
</script>
<style scoped lang='scss'></style>
